﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_ProcecureSubBusiness : BaseBusiness<PB_ProcecureSub>, IPB_ProcecureSubBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_ProcecureSubBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }
        #region 外部接口

        public async Task<PageResult<PB_ProcecureSub>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_ProcecureSub>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_ProcecureSub, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }
            
        public async Task<PB_ProcecureSub> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        [DataAddLog(UserLogType.工序管理, "Name", "工序管理")]
        [DataRepeatValidate(new string[] { "Code", "Name" }, new string[] { "工序编号", "工序名称" })]
        public async Task AddDataAsync(PB_ProcecureSub data)
        {
            await InsertAsync(data);
        }

        [DataEditLog(UserLogType.工序管理, "Name", "工序管理")]
        [DataRepeatValidate(new string[] { "Code", "Name" }, new string[] { "工序编号", "工序名称" })]
        public async Task UpdateDataAsync(PB_ProcecureSub data)
        {
            await UpdateAsync(data);
        }

        [DataDeleteLog(UserLogType.工序管理, "Name", "工序管理")]
        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public async Task<List<PB_ProcecureSubDTO>> GetDataListAsyncs(string parentid)
        {
            Expression<Func<PB_ProcecureSub, PB_Supplier, PB_ProcecureMain, PB_ProcecureSubDTO>> select = (a, e, f) => new PB_ProcecureSubDTO
            {
                SupplierName = e.Name,
                ProcecureMainName = f.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join e in Db.GetIQueryable<PB_Supplier>() on a.SupplierId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_ProcecureMain>() on a.ParentId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    select @select.Invoke(a, e, f);
            ////筛选
            //if (!parentid.IsNullOrEmpty())
            //{
            //    q = q.Where(w => w.ParentId == parentid);
            //}
            var res = await q.Where(x => x.ParentId == parentid).ToListAsync();

            return res;
        }


        public async Task<List<PB_ProcecureSub>> GetDatalist(string ParentId)
        {
            //   //筛选
            if (!ParentId.IsNullOrEmpty())
            {
                var q = GetIQueryable().Where(x => x.ParentId == ParentId);
                var res = await q.ToListAsync();
                return res;
            } 
            else
            {
                return null;
            }
        }
        public IQueryable<T> GetQueryable<T>() where T : class, new()
        {
            return Db.GetIQueryable<T>();
        }
        public async Task<List<PB_ProcecureListDto>> GetDataListByDepartment(string DeptId)
        {
            Expression<Func<PB_ProcecureSub, PB_ProcecureMain,  PB_ProcecureListDto>> select = (a, b) => new PB_ProcecureListDto
            {
                ManName = b.Name,
                ManCode = b.Code,
                Deptid=b.DeptId,
            };
            select = select.BuildExtendSelectExpre();
            var q_DesignList = GetIQueryable();
            var q = from a in q_DesignList.AsExpandable()
                        //联合PB_ProcecureSub表
                    join b in Db.GetIQueryable<PB_ProcecureMain>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            q = q.Where(m => m.Deptid == DeptId);
            return await q.ToListAsync();
        }
        public async Task<List<ProcecureSubTreeDTO>> GetTreeSubListAsyncs()
        {
            var list = await Db.GetIQueryable<PB_ProcecureMain>().ToListAsync();
            List<ProcecureSubTreeDTO> listData = new List<ProcecureSubTreeDTO>();
            foreach (var item in list)
            {
                ProcecureSubTreeDTO tree = new ProcecureSubTreeDTO();
                tree.Id = item.Id;
                tree.Text = item.Name;
                tree.Value = item.Id;
                listData.Add(tree);
                await GetItemTree(item.Id, listData);
            }
            var treeList = listData
                .Select(x => new ProcecureSubTreeDTO
                {
                    Id = x.Id,
                    ParentId = x.ParentId,
                    Text = x.Text,
                    Value = x.Id,
                }).ToList();
            return TreeHelper.BuildTree(treeList);
        }

        public async Task<List<ProcecureSubTreeDTO>> GetItemTree(string ParentId, List<ProcecureSubTreeDTO> ListData)
        {
            var childrenItem = await Db.GetIQueryable<PB_ProcecureSub>().Where(x => x.ParentId == ParentId).ToListAsync();
            //List<string> aaa=new List<string>()
            //await Db.GetIQueryable<PB_ProcecureSub>().Where(x => x.ParentId== ParentId && list.c(x.)).ToListAsync();
            foreach (var item in childrenItem)
            {
                ProcecureSubTreeDTO treedata = new ProcecureSubTreeDTO();
                treedata.Id = item.Id;
                treedata.ParentId = item.ParentId;
                treedata.Text = item.Name;
                treedata.Value = item.Id;
                ListData.Add(treedata);
              
            }
            return ListData;
        }

        public async Task<PageResult<PB_ProcecureSubDTO>> GetDataListAsyncsok(PageInput<ConditionDTO> input, string parentid)
        {
            var search = input.Search;
            Expression<Func<PB_ProcecureSub, PB_Supplier, PB_ProcecureMain, PB_ProcecureSubDTO>> select = (a, e, f) => new PB_ProcecureSubDTO
            {
                SupplierName = e.Name,
                ProcecureMainName = f.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join e in Db.GetIQueryable<PB_Supplier>() on a.SupplierId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_ProcecureMain>() on a.ParentId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    select @select.Invoke(a, e, f);
            var where = LinqHelper.True<PB_ProcecureSubDTO>();
            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_ProcecureSubDTO, bool>(
                    ParsingConfig.Default, false, $@"Name.Contains(@0) or Code.Contains(@0) or SimpleName.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }


            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// 获取今天报工的工序
        /// </summary>
        /// <returns></returns>
        public async Task<List<RapidqualitySubDays>> GetRapidqualitySubDaysList()
        {
          
            StringBuilder sql = new StringBuilder();

             sql.AppendLine("SELECT");
            sql.AppendLine("  *");
            sql.AppendLine("FROM");
            sql.AppendLine(" (");
            sql.AppendLine("  SELECT");

            sql.AppendLine("  PB_ProcecureSub.Id,");
            sql.AppendLine(" PB_ProcecureSub.`Name` ");

            sql.AppendLine(" FROM");

            sql.AppendLine(" PB_JobBooking");

            sql.AppendLine("  LEFT JOIN Base_Device ON PB_JobBooking.DeviceId = Base_Device.Id");

            sql.AppendLine("LEFT JOIN PB_ProcecureSub ON Base_Device.ProcecureSubId = PB_ProcecureSub.Id");

            sql.AppendLine(" WHERE");

            sql.AppendLine("  TO_DAYS(PB_JobBooking.ReportTime) = TO_DAYS(");
            sql.AppendLine("  now()) UNION ALL");

            sql.AppendLine(" SELECT");

            sql.AppendLine(" PB_ProcecureSub.Id,");
            sql.AppendLine(" PB_ProcecureSub.`Name` ");

            sql.AppendLine(" FROM");

            sql.AppendLine(" PB_CirculationBill");

            sql.AppendLine(" LEFT JOIN PB_ProcecureSub ON PB_CirculationBill.ProcedureId = PB_ProcecureSub.Id");

            sql.AppendLine(" WHERE");

            sql.AppendLine(" TO_DAYS(PB_CirculationBill.SendTime) = TO_DAYS(");
            sql.AppendLine("  now())");
            sql.AppendLine(" ) AS T");
            sql.AppendLine("GROUP BY");

            sql.AppendLine(" T.Id,");

            sql.AppendLine(" T.`Name`");
            var res =await Db.GetListBySqlAsync<RapidqualitySubDays>(sql.ToString());
            return res;
        }

        /// <summary>
        /// 获取今天报工的工序
        /// </summary>
        /// <returns></returns>
        public async Task<PageResult<WorkReportWorklist>> GetWorkReportWorklist(PageInput<WorkReportWorkSearch> input)
        {
            if (input.Search.Type == 0)
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine(" SELECT");
                sql.AppendLine("a.*  from (");
                sql.AppendLine("SELECT");
                sql.AppendLine("PB_CirculationBill.Id 'Id',");
                sql.AppendLine("PB_Material.Spec 'MaterialSpec',");
                sql.AppendLine("PB_Material.`Name` 'MaterialName',");
                sql.AppendLine("Base_User.RealName 'RealName',");
                sql.AppendLine("Base_Department.`Name` 'DepartmentName',");
                sql.AppendLine("PB_CirculationBill.WorkReportQuantity 'Nums',");
                sql.AppendLine("PB_CirculationBill.QualityNums 'ReturnNums',");
                sql.AppendLine("PB_CirculationBill.StatisticalQuantity 'StatisticsNums',");
                sql.AppendLine("'PB_CirculationBill' AS 'PB_CirculationBill',");
                sql.AppendLine("PB_ProcecureSub.`Name` SubName,");
                sql.AppendLine("PB_ProcecureSub.`Id` SubId,");
                sql.AppendLine("PB_CirculationBill.SendTime 'SendTime'");
                sql.AppendLine("FROM");
                sql.AppendLine("PB_CirculationBill");
                sql.AppendLine("INNER JOIN PB_ProcecureSub ON PB_CirculationBill.ProcedureId = PB_ProcecureSub.Id");
                sql.AppendLine("INNER JOIN PB_Material ON PB_CirculationBill.MaterialId = PB_Material.Id");
                sql.AppendLine("INNER JOIN Base_Department ON PB_CirculationBill.DeptId = Base_Department.Id");
                sql.AppendLine("INNER JOIN Base_User ON PB_CirculationBill.WorkerId = Base_User.Id");
                sql.AppendLine(") AS a ");
                sql.AppendLine("WHERE  a.Nums>0 AND  a.ReturnNums IS NULL");
                if (!input.Search.SubId.IsNullOrEmpty())
                {
                    sql.AppendLine($"AND a.SubId = '{input.Search.SubId}'  ");
                }
                sql.AppendLine("ORDER BY a.SendTime DESC ");
                var res = await Db.GetListBySqlAsync<WorkReportWorklist>(sql.ToString());
                int pagecount;//总页数
                List<WorkReportWorklist> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
                List<WorkReportWorklist> productes = new List<WorkReportWorklist>();//用来存储要展示的数据
                int pagees = listpro_down.Count;//所有数据的总条数                             //计算总页数
                if (pagees % input.PageRows == 0)
                {
                    pagecount = pagees / input.PageRows;
                }
                else
                {
                    pagecount = (pagees / input.PageRows) + 1;
                }
                productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
                return new PageResult<WorkReportWorklist> { Data = productes, Total = pagees };
            }
            else if(input.Search.Type==1) {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine(" SELECT");
                sql.AppendLine("a.*  from (");
                sql.AppendLine("SELECT");
                sql.AppendLine("PB_CirculationBill.Id 'Id',");
                sql.AppendLine("PB_Material.Spec 'MaterialSpec',");
                sql.AppendLine("PB_Material.`Name` 'MaterialName',");
                sql.AppendLine("Base_User.RealName 'RealName',");
                sql.AppendLine("Base_Department.`Name` 'DepartmentName',");
                sql.AppendLine("PB_CirculationBill.WorkReportQuantity 'Nums',");
                sql.AppendLine("PB_CirculationBill.QualityNums 'ReturnNums',");
                sql.AppendLine("PB_CirculationBill.StatisticalQuantity 'StatisticsNums',");
                sql.AppendLine("'PB_CirculationBill' AS 'PB_CirculationBill',");
                sql.AppendLine("PB_ProcecureSub.`Name` SubName,");
                sql.AppendLine("PB_ProcecureSub.`Id` SubId,");
                sql.AppendLine("PB_CirculationBill.SendTime 'SendTime'");
                sql.AppendLine("FROM");
                sql.AppendLine("PB_CirculationBill");
                sql.AppendLine("INNER JOIN PB_ProcecureSub ON PB_CirculationBill.ProcedureId = PB_ProcecureSub.Id");
                sql.AppendLine("INNER JOIN PB_Material ON PB_CirculationBill.MaterialId = PB_Material.Id");
                sql.AppendLine("INNER JOIN Base_Department ON PB_CirculationBill.DeptId = Base_Department.Id");
                sql.AppendLine("INNER JOIN Base_User ON PB_CirculationBill.WorkerId = Base_User.Id");
                sql.AppendLine("WHERE");
                sql.AppendLine("PB_CirculationBill.QualityNums >0");
                sql.AppendLine("AND PB_CirculationBill.StatisticalQuantity IS NULL");
                sql.AppendLine("or PB_CirculationBill.StatisticalQuantity=0");
                sql.AppendLine(") AS a ");
                sql.AppendLine("WHERE a.ReturnNums > 0 AND(a.StatisticsNums = 0 OR a.StatisticsNums IS NULL)");
                if (!input.Search.SubId.IsNullOrEmpty())
                {
                    sql.AppendLine($"AND a.SubId = '{input.Search.SubId}' ");
                }
                var res = await Db.GetListBySqlAsync<WorkReportWorklist>(sql.ToString());
                int pagecount;//总页数
                List<WorkReportWorklist> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
                List<WorkReportWorklist> productes = new List<WorkReportWorklist>();//用来存储要展示的数据
                int pagees = listpro_down.Count;//所有数据的总条数
                                                //计算总页数
                if (pagees % input.PageRows == 0)
                {
                    pagecount = pagees / input.PageRows;
                }
                else
                {
                    pagecount = (pagees / input.PageRows) + 1;
                }
                productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
                return new PageResult<WorkReportWorklist> { Data = productes, Total = pagees };
            }
            return new PageResult<WorkReportWorklist>();

        }
        /// <summary>
        /// 获取获取当天的报工历史
        /// </summary>
        /// <returns></returns>
        public async Task<PageResult<WorkReportWorklist>> GetWorkReportHistory(PageInput<WorkReportWorkSearch> input)
        {

            StringBuilder sql = new StringBuilder();
            sql.AppendLine("");
            sql.AppendLine("SELECT");
            sql.AppendLine("a.*");
            sql.AppendLine("FROM");
            sql.AppendLine("(");
            sql.AppendLine("SELECT");
            sql.AppendLine("PB_JobBooking.Id 'Id',");
            sql.AppendLine("PB_Material.Spec 'MaterialSpec',");
            sql.AppendLine("PB_Material.`Name` 'MaterialName',");
            sql.AppendLine("Base_User.RealName 'RealName',");
            sql.AppendLine("Base_Department.`Name` 'DepartmentName',");
            sql.AppendLine("PB_JobBooking.Nums 'Nums',");
            sql.AppendLine("PB_JobBooking.ReturnNums 'ReturnNums',");
            sql.AppendLine("PB_JobBooking.StatisticsNums 'StatisticsNums',");
            sql.AppendLine("'PB_JobBooking' AS 'Type',");
            sql.AppendLine("PB_ProcecureSub.`Name` SubName,");
            sql.AppendLine("PB_ProcecureSub.`Id` SubId,");
            sql.AppendLine("PB_JobBooking.ReportTime 'SendTime'");
            sql.AppendLine("FROM");
            sql.AppendLine("PB_JobBooking");
            sql.AppendLine("INNER JOIN Base_Device ON PB_JobBooking.DeviceId = Base_Device.Id");
            sql.AppendLine("INNER JOIN PB_ProcecureSub ON Base_Device.ProcecureSubId = PB_ProcecureSub.Id");
            sql.AppendLine("INNER JOIN PB_Material ON PB_JobBooking.MaterialId = PB_Material.Id");
            sql.AppendLine("INNER JOIN Base_Department ON PB_JobBooking.DeptId = Base_Department.Id");
            sql.AppendLine("INNER JOIN Base_User ON PB_JobBooking.ReportUserId = Base_User.Id");
            sql.AppendLine("WHERE");
            sql.AppendLine("PB_JobBooking.StatisticsNums > 0");
            sql.AppendLine("UNION ALL");
            sql.AppendLine("SELECT");
            sql.AppendLine("PB_CirculationBill.Id 'Id',");
            sql.AppendLine("PB_Material.Spec 'MaterialSpec',");
            sql.AppendLine("PB_Material.`Name` 'MaterialName',");
            sql.AppendLine("Base_User.RealName 'RealName',");
            sql.AppendLine("Base_Department.`Name` 'DepartmentName',");
            sql.AppendLine("PB_CirculationBill.WorkReportQuantity 'Nums',");
            sql.AppendLine("PB_CirculationBill.QualityNums 'ReturnNums',");
            sql.AppendLine("PB_CirculationBill.StatisticalQuantity 'StatisticsNums',");
            sql.AppendLine("'PB_CirculationBill' AS 'PB_CirculationBill',");
            sql.AppendLine("PB_ProcecureSub.`Name` SubName,");
            sql.AppendLine("PB_ProcecureSub.`Id` SubId,");
            sql.AppendLine("PB_CirculationBill.SendTime 'SendTime'");
            sql.AppendLine("FROM");
            sql.AppendLine("PB_CirculationBill");
            sql.AppendLine("INNER JOIN PB_ProcecureSub ON PB_CirculationBill.ProcedureId = PB_ProcecureSub.Id");
            sql.AppendLine("INNER JOIN PB_Material ON PB_CirculationBill.MaterialId = PB_Material.Id");
            sql.AppendLine("INNER JOIN Base_Department ON PB_CirculationBill.DeptId = Base_Department.Id");
            sql.AppendLine("INNER JOIN Base_User ON PB_CirculationBill.WorkerId = Base_User.Id");
            sql.AppendLine("WHERE");
            sql.AppendLine("PB_CirculationBill.StatisticalQuantity > 0");
            sql.AppendLine(") AS a");
            sql.AppendLine("WHERE");
            sql.AppendLine("a.SubId = '"+input.Search.SubId+"'");
            sql.Append("and a.StatisticsNums>0");
            var res = await Db.GetListBySqlAsync<WorkReportWorklist>(sql.ToString());
            List<WorkReportWorklist> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
            List<WorkReportWorklist> productes = new List<WorkReportWorklist>();//用来存储要展示的数据
            int pagecount;//总页数
            int pagees = listpro_down.Count;//所有数据的总条数                             //计算总页数
            if (pagees % input.PageRows == 0)
            {
                pagecount = pagees / input.PageRows;
            }
            else
            {
                pagecount = (pagees / input.PageRows) + 1;
            }
            productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
            return new PageResult<WorkReportWorklist> { Data = productes, Total = pagees };
        }

        public async Task BatchSave_Statistics(BatchSave_Statistics Data)
        {
            List<PB_CirculationBill> pB_CirculationBills = new List<PB_CirculationBill>();
            if (Data.Type == 0)
            {
                //获取要质检的数据
                for (int i = 0; i < Data.BatchData.Count; i++)
                {
                    var PB_PB_CirculationBill = await Db.GetIQueryable<PB_CirculationBill>().Where(m => m.Id == Data.BatchData[i].Id).FirstOrDefaultAsync();
                    PB_CirculationBill pB_CirculationBill = new PB_CirculationBill();
                    pB_CirculationBill.Id = PB_PB_CirculationBill.Id;
                    pB_CirculationBill.CreateTime = PB_PB_CirculationBill.CreateTime;
                    pB_CirculationBill.CreatorId = PB_PB_CirculationBill.CreatorId;
                    pB_CirculationBill.Deleted = PB_PB_CirculationBill.Deleted;
                    pB_CirculationBill.Type = PB_PB_CirculationBill.Type;
                    pB_CirculationBill.FactoryId = PB_PB_CirculationBill.FactoryId;
                    pB_CirculationBill.DeptId = PB_PB_CirculationBill.DeptId;
                    pB_CirculationBill.DeviceId = PB_PB_CirculationBill.DeviceId;
                    pB_CirculationBill.TaskId = PB_PB_CirculationBill.TaskId;
                    pB_CirculationBill.DispatchId = PB_PB_CirculationBill.DispatchId;
                    pB_CirculationBill.DispatchDetailId = PB_PB_CirculationBill.DispatchDetailId;
                    pB_CirculationBill.ProcedureId = PB_PB_CirculationBill.ProcedureId;
                    pB_CirculationBill.TrayId = PB_PB_CirculationBill.TrayId;
                    pB_CirculationBill.MaterialId = PB_PB_CirculationBill.MaterialId;
                    pB_CirculationBill.TaskQuantity = PB_PB_CirculationBill.TaskQuantity;
                    pB_CirculationBill.WorkReportQuantity = PB_PB_CirculationBill.WorkReportQuantity;
                    pB_CirculationBill.WorkerId = PB_PB_CirculationBill.WorkerId;
                    pB_CirculationBill.SendTime = PB_PB_CirculationBill.SendTime;
                    pB_CirculationBill.StatisticalQuantity = PB_PB_CirculationBill.StatisticalQuantity;
                    pB_CirculationBill.Statistician = PB_PB_CirculationBill.Statistician;
                    pB_CirculationBill.StatisticalTime = PB_PB_CirculationBill.StatisticalTime;
                    pB_CirculationBill.Receiver = PB_PB_CirculationBill.Receiver;
                    pB_CirculationBill.ReceivingTime = PB_PB_CirculationBill.ReceivingTime;
                    pB_CirculationBill.ReceivingQuantity = PB_PB_CirculationBill.ReceivingQuantity;
                    pB_CirculationBill.Reamrk = PB_PB_CirculationBill.Reamrk;
                    pB_CirculationBill.Status = PB_PB_CirculationBill.Status;
                    pB_CirculationBill.QrCode = PB_PB_CirculationBill.QrCode;
                    pB_CirculationBill.LocationId = PB_PB_CirculationBill.LocationId;
                    pB_CirculationBill.ReadyNums = PB_PB_CirculationBill.ReadyNums;
                    pB_CirculationBill.DispatchRemark = PB_PB_CirculationBill.DispatchRemark;
                    pB_CirculationBill.PackId = PB_PB_CirculationBill.PackId;
                    pB_CirculationBill.IsOutsourcing = PB_PB_CirculationBill.IsOutsourcing;
                    pB_CirculationBill.QualityNums = Data.BatchData[i].Nums;
                    pB_CirculationBill.QualityUserId = _operator.UserId;
                    pB_CirculationBill.QualityTime = DateTime.Now;
                    pB_CirculationBill.TaskDetailId = PB_PB_CirculationBill.TaskDetailId;
                    pB_CirculationBill.SubordinateProduct = PB_PB_CirculationBill.SubordinateProduct;
                    pB_CirculationBill.NoticeId = PB_PB_CirculationBill.NoticeId;
                    pB_CirculationBills.Add(pB_CirculationBill);
                    
                }
                await Db.UpdateAsync(pB_CirculationBills);

            }
            else if (Data.Type == 1)
            {
                for (int i = 0; i < Data.BatchData.Count; i++)
                {
                    //获取要统计的数据
                    var PB_PB_CirculationBill = await Db.GetIQueryable<PB_CirculationBill>().Where(m => m.Id == Data.BatchData[i].Id).FirstOrDefaultAsync();
                    PB_CirculationBill pB_CirculationBill = new PB_CirculationBill();
                    pB_CirculationBill.Id = PB_PB_CirculationBill.Id;
                    pB_CirculationBill.CreateTime = PB_PB_CirculationBill.CreateTime;
                    pB_CirculationBill.CreatorId = PB_PB_CirculationBill.CreatorId;
                    pB_CirculationBill.Deleted = PB_PB_CirculationBill.Deleted;
                    pB_CirculationBill.Type = PB_PB_CirculationBill.Type;
                    pB_CirculationBill.FactoryId = PB_PB_CirculationBill.FactoryId;
                    pB_CirculationBill.DeptId = PB_PB_CirculationBill.DeptId;
                    pB_CirculationBill.DeviceId = PB_PB_CirculationBill.DeviceId;
                    pB_CirculationBill.TaskId = PB_PB_CirculationBill.TaskId;
                    pB_CirculationBill.DispatchId = PB_PB_CirculationBill.DispatchId;
                    pB_CirculationBill.DispatchDetailId = PB_PB_CirculationBill.DispatchDetailId;
                    pB_CirculationBill.ProcedureId = PB_PB_CirculationBill.ProcedureId;
                    pB_CirculationBill.TrayId = PB_PB_CirculationBill.TrayId;
                    pB_CirculationBill.MaterialId = PB_PB_CirculationBill.MaterialId;
                    pB_CirculationBill.TaskQuantity = PB_PB_CirculationBill.TaskQuantity;
                    pB_CirculationBill.WorkReportQuantity = PB_PB_CirculationBill.WorkReportQuantity;
                    pB_CirculationBill.WorkerId = PB_PB_CirculationBill.WorkerId;
                    pB_CirculationBill.SendTime = PB_PB_CirculationBill.SendTime;
                    pB_CirculationBill.StatisticalQuantity = Data.BatchData[i].Nums;
                    pB_CirculationBill.Statistician = _operator.UserId;
                    pB_CirculationBill.StatisticalTime = DateTime.Now;
                    pB_CirculationBill.Receiver = PB_PB_CirculationBill.Receiver;
                    pB_CirculationBill.ReceivingTime = PB_PB_CirculationBill.ReceivingTime;
                    pB_CirculationBill.ReceivingQuantity = PB_PB_CirculationBill.ReceivingQuantity;
                    pB_CirculationBill.Reamrk = PB_PB_CirculationBill.Reamrk;
                    pB_CirculationBill.Status = PB_PB_CirculationBill.Status;
                    pB_CirculationBill.QrCode = PB_PB_CirculationBill.QrCode;
                    pB_CirculationBill.LocationId = PB_PB_CirculationBill.LocationId;
                    pB_CirculationBill.ReadyNums = PB_PB_CirculationBill.ReadyNums;
                    pB_CirculationBill.DispatchRemark = PB_PB_CirculationBill.DispatchRemark;
                    pB_CirculationBill.PackId = PB_PB_CirculationBill.PackId;
                    pB_CirculationBill.IsOutsourcing = PB_PB_CirculationBill.IsOutsourcing;
                    pB_CirculationBill.QualityNums = PB_PB_CirculationBill.QualityNums;
                    pB_CirculationBill.QualityUserId = PB_PB_CirculationBill.QualityUserId;
                    pB_CirculationBill.QualityTime = DateTime.Now;
                    pB_CirculationBill.TaskDetailId = PB_PB_CirculationBill.TaskDetailId;
                    pB_CirculationBill.SubordinateProduct = PB_PB_CirculationBill.SubordinateProduct;
                    pB_CirculationBill.NoticeId = PB_PB_CirculationBill.NoticeId;
                    pB_CirculationBills.Add(pB_CirculationBill);
                 
                }
                await Db.UpdateAsync(pB_CirculationBills);
            }
        }

        public  async Task<List<PB_ProcecureSub>> GeFinishe()
        {
            StringBuilder sql = new StringBuilder();

            sql.AppendLine(" SELECT");

            sql.AppendLine("  t.*");
            sql.AppendLine("FROM");
            sql.AppendLine(" (");
            sql.AppendLine(" SELECT");

            sql.AppendLine(" c.Id,");
            sql.AppendLine(" c.`Name` ");

            sql.AppendLine(" FROM");

            sql.AppendLine(" PB_JobBooking AS a");

            sql.AppendLine(" LEFT JOIN Base_Device AS b ON a.DeviceId = b.Id");

            sql.AppendLine(" LEFT JOIN PB_ProcecureSub AS c ON b.ProcecureSubId = c.Id");

            sql.AppendLine(" GROUP BY");

            sql.AppendLine(" c.Id");
            sql.AppendLine(" ) AS b");
            sql.AppendLine("LEFT JOIN(SELECT Id, NAME FROM PB_ProcecureSub ) AS t ON t.Id != b.Id");
            var res = await Db.GetListBySqlAsync<PB_ProcecureSub>(sql.ToString());
            return res;
        }

        /// <summary>
        /// 获取日产量报工汇总
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<ProceduredaySummary>> GetProceduredaySummary(PageInput<IT_LocalDetailDtolistContionDTO> input)
        {
            StringBuilder sql = new StringBuilder();
             sql.AppendLine("SELECT");
            sql.AppendLine("SendTime,");
            sql.AppendLine("DeptName,");
            sql.AppendLine("sum(XLNum) XLNum,");
            sql.AppendLine("sum(XLWeight) XLWeight,");
            sql.AppendLine("sum(HJNum) HJNum,");
            sql.AppendLine("sum(HJWeight) HJWeight,");
            sql.AppendLine("sum(PTNum) PTNum,");
            sql.AppendLine("sum(PTWeight) PTWeight,");
            sql.AppendLine("sum(QTNum) QTNum,");
            sql.AppendLine("sum(QTWeight) QTWeight");
            sql.AppendLine("FROM");
            sql.AppendLine("V_WorkshopTotal_All");
            sql.AppendLine("GROUP BY");
            sql.AppendLine("SendTime,");
            sql.AppendLine("DeptName");
            sql.AppendLine("ORDER BY  SendTime "+input.SortType+"");
            var res = await Db.GetListBySqlAsync<ProceduredaySummary>(sql.ToString());
            #region   分页处理数据   有bug 没有按照主数据进行处理
            int pagecount;//总页数
            List<ProceduredaySummary> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
            List<ProceduredaySummary> productes = new List<ProceduredaySummary>();//用来存储要展示的数据
            int pagees = listpro_down.Count;//所有数据的总条数
                                            //计算总页数
            if (pagees % input.PageRows == 0)
            {
                pagecount = pagees / input.PageRows;
            }
            else
            {
                pagecount = (pagees / input.PageRows) + 1;
            }
            productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
            return new PageResult<ProceduredaySummary> { Data = productes, Total = pagees };
            #endregion
        }

        public async Task<PageResult<SprayList>> GetSprayList(PageInput<IT_LocalDetailDtolistContionDTO> input)
        {
            StringBuilder sql = new StringBuilder();
     
            sql.AppendLine("SELECT");
            sql.AppendLine("t.WorkName,");
            sql.AppendLine(" date_format(t.ReportTime, '%Y-%m-%d') DispatchDate,");
            sql.AppendLine("t.`Name`,");
            sql.AppendLine("t.SubName,");
            sql.AppendLine("t.`IsRefurbishment`,");
            sql.AppendLine("IFNULL(SUM(t.Nums), 0) Nums,");
            sql.AppendLine("IFNULL(SUM(t.Nums * t.Weight)/1000, 0) Weight,");
            sql.AppendLine("t.`Going` ");
            sql.AppendLine("FROM");
            sql.AppendLine("(");
            sql.AppendLine("SELECT");
            sql.AppendLine("department.`Name` WorkName,");
            sql.AppendLine("job.Nums,");
            sql.AppendLine("IFNULL(mater.Weight, 0) Weight,");
            sql.AppendLine("'喷涂' AS SubName,");
            sql.AppendLine("CASE");
            sql.AppendLine("WHEN detail.IsRefurbishment = 0 THEN");
            sql.AppendLine("'翻新'");
            sql.AppendLine("WHEN detail.IsRefurbishment = 1 THEN");
            sql.AppendLine(" '新制'");
            sql.AppendLine("WHEN detail.IsRefurbishment = 2 THEN");
            sql.AppendLine(" '非生产'");
            sql.AppendLine(" WHEN detail.IsRefurbishment = 3 THEN");
            sql.AppendLine("'维修改制'");
            sql.AppendLine("WHEN detail.IsRefurbishment = 4 THEN");
            sql.AppendLine("'组装' ELSE ''");
            sql.AppendLine("END IsRefurbishment,");
            sql.AppendLine("job.ReportTime,");
            sql.AppendLine("shifttype.`Name`,");
            sql.AppendLine("'仓库' AS 'Going'");
            sql.AppendLine("FROM");
            sql.AppendLine("PB_JobBooking AS job");
            sql.AppendLine("INNER JOIN PB_CirculationBill AS bill ON job.CirBillId = bill.Id");
            sql.AppendLine("INNER JOIN PB_Material AS mater ON job.MaterialId = mater.Id");
            sql.AppendLine("INNER JOIN PB_DispatchDetail AS detail ON bill.DispatchDetailId = detail.Id");
            sql.AppendLine("INNER JOIN PB_Dispatch AS dispatch ON detail.ParentId = dispatch.Id");
            sql.AppendLine("INNER JOIN PB_ShiftType AS shifttype ON dispatch.TeamType = shifttype.Id");
            sql.AppendLine("INNER JOIN Base_Department AS department ON job.WorkshopId = department.Id");
            sql.AppendLine(") AS t");
            sql.AppendLine("GROUP BY");
            sql.AppendLine("t.WorkName,");
            sql.AppendLine("t.SubName,");
            sql.AppendLine("t.IsRefurbishment,");
            sql.AppendLine("  date_format(t.ReportTime, '%Y-%m-%d'),");
            sql.AppendLine("t.`Name` ");
            sql.AppendLine("ORDER BY  date_format(t.ReportTime, '%Y-%m-%d') " + input.SortType + "");
            var res = await Db.GetListBySqlAsync<SprayList>(sql.ToString());
            #region   分页处理数据   有bug 没有按照主数据进行处理
            int pagecount;//总页数
            List<SprayList> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
            List<SprayList> productes = new List<SprayList>();//用来存储要展示的数据
            int pagees = listpro_down.Count;//所有数据的总条数
                                            //计算总页数
            if (pagees % input.PageRows == 0)
            {
                pagecount = pagees / input.PageRows;
            }
            else
            {
                pagecount = (pagees / input.PageRows) + 1;
            }
            productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
            return new PageResult<SprayList> { Data = productes, Total = pagees };
            #endregion


        }

    }
   



    #endregion

    #region 私有成员

    #endregion
}
